<?php
namespace App\Controller;

use App\Model\CommentModel;
use App\Model\TrendsModel;
use App\Model\UserModel;
use lib\Model;
use lib\View;

class UserController
{
    public function login(){
        return new View('login');
    }
    public function register(){
        return new View('register');
    }
    public function index(){
        return new View('index');
    }
    public function do_register(){
         $array=[];
         $username=$this->input('username');
         $password=$this->input('password');
        $array['username']=$username;
        $array['password']=$password;
        $user=new UserModel('user','uid');
        $res=$user->registercheck();
        if ($res){
           // print_r($res);exit();
            return new View('register',['res'=>$res]);
        }
        $user->save($array);
       // print_r($array);exit();
       return new View('login');

    }
   public function do_login()
   {
       $error=[];
       $array=[];
       $username=$this->input('username');
       $password=$this->input('password');
       $array['username']=$username;
       $array['password']=$password;
       $user=new UserModel('user','uid');
       $userinfo=$user->get($array);
       if(count($userinfo)>0){
       $trends=$user->join(['trend'=>'uid'],['trend.uid'=>$userinfo[0]['uid']]);
           $_SESSION['pic']=$userinfo[0]['pic'];
           $_SESSION['uid']=$userinfo[0]['uid'];
           $_SESSION['username']=$username;
           $_SESSION['userinfo']=$userinfo;
           $comment=new CommentModel('comment','cid');
           $comments=$user->join(['comment'=>'uid']);
           $_SESSION['comments']=$comments;
       return new View('index',['trends'=>$trends]);
   }else{
       $error['loginerror']='用户名或密码错误';
           return new View('login',['error'=>$error]);
   }
   }
   public function userEdite(){
       $username=isset($_SESSION['username'])?$_SESSION['username']:'';
        $user=new UserModel('user','uid');
        $userinfo=$user->get(['username'=>$username]);
       // print_r($rows);exit();
        return new View('useredite',['userinfo'=>$userinfo,'username'=>$username]);
   }
   public function userIndex(){
       $array=$_POST;
       $username=$this->input('username');
       $avater=isset($_FILES['pic'])?$_FILES['pic']:'';
       $user=new UserModel('user','uid');
       $pic1=$user->checkpic($avater,$username);
       $pic=str_replace('\\','/',$pic1);
       $array['pic']=$pic;
     // print_r($array);exit();
       $user->save($array);
      return new View('userindex',['username'=>$username,'array'=>$array]);
   }
    public function input($name)
    {
        return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}